package com.two.screen.water.balance.ui.activity

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import com.alibaba.android.arouter.facade.annotation.Route
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.github.gzuliyujiang.dialog.DialogConfig
import com.github.gzuliyujiang.dialog.DialogStyle
import com.github.gzuliyujiang.wheelpicker.DatimePicker
import com.github.gzuliyujiang.wheelpicker.annotation.DateMode
import com.github.gzuliyujiang.wheelpicker.annotation.TimeMode
import com.github.gzuliyujiang.wheelpicker.entity.DateEntity
import com.github.gzuliyujiang.wheelpicker.entity.DatimeEntity
import com.jakewharton.rxbinding2.view.RxView
import com.two.screen.water.balance.R
import com.two.screen.water.balance.bean.BaseBean
import com.two.screen.water.balance.bean.OrderServerBean
import com.two.screen.water.balance.net.api.DataApi
import com.two.screen.water.balance.net.api.NormalApi
import com.two.screen.water.balance.net.observer.NormalObserver
import com.two.screen.water.balance.net.observer.StatusLayoutObserver
import com.two.screen.water.balance.print.PrinterAll
import com.two.screen.water.balance.print.bean.PrintOrderBean
import com.two.screen.water.balance.print.bean.PrintServerCollectOrderBean
import com.two.screen.water.balance.ui.App
import com.two.screen.water.balance.ui.activity.base.BaseActivity
import com.two.screen.water.balance.utils.*
import com.two.screen.water.balance.widget.DividerItemDecoration
import kotlinx.android.synthetic.main.activity_order_server.*
import java.util.*
import java.util.concurrent.TimeUnit

/*历史订单、本地订单*/
@Route(path = ARouterUtils.OrderServerActivity)
class OrderServerActivity : BaseActivity() {
    override fun getContentLayout(): Any = R.layout.activity_order_server
    lateinit var mSearchAdapter: SearchAdapter
    lateinit var mProductAdapter: ProductAdapter

    /*请求条件*/
    private var mDateBegin: String? = null
    private var mDateEnd: String? = null
    private var mStartEntity: DatimeEntity? = null
    private var mPage = 1 // 第几页
    private var mPageSize = 20 // 一页有几条
    private var mCurStatePay: Int? = 5 //支付状态  支付状态 0未支付 5 已支付
    private var mCurPayType: Int? = null //支付类型  支付类型 0 => '现金支付', 4 => '会员卡支付', 6 => '聚合支付',7 => '微会员支付'
    private var mSearchDay: Int? = null //说明： 快捷时间类型 1：今日、3：近3天、7近7天、30 近30天

    private var mDialogStatePayIndex = 2
    private var mDialogPayTypeIndex = 0
    private var mPayTypeArray: Array<String> = arrayOf("全部", "现金支付", "会员卡支付", "聚合支付", "微会员支付", "付款码支付")


    private var mStartPicker: DatimePicker? = null
    private var mEndPicker: DatimePicker? = null

    protected var mData: OrderServerBean? = null

    override fun initView(savedInstanceState: Bundle?) {

    }


    override fun initData() {
        initSearchRecyclerView()
        initProductRecyclerView()
        getData()
    }

    @SuppressLint("ClickableViewAccessibility", "CheckResult", "SetTextI18n")
    override fun initListener() {
        mGoBackLayout.setOnClickListener { goBack() }
        mTodaySearchTv.setOnClickListener {
            updateSearchDayUI(mTodaySearchTv, 1)
        }
        mThreeDayTv.setOnClickListener {
            updateSearchDayUI(mThreeDayTv, 3)
        }
        mSevenSearchTv.setOnClickListener {
            updateSearchDayUI(mSevenSearchTv, 7)
        }
        mMonthSearchTv.setOnClickListener {
            updateSearchDayUI(mMonthSearchTv, 30)
        }

        RxView.clicks(mPayStateTv)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                AlertDialog.Builder(this)
                    .setTitle("请选择支付状态:")
                    .setCancelable(true)
                    .setSingleChoiceItems(DataApi.mStatePayArray, mDialogStatePayIndex) { dialog, which ->
                        //支付状态 0未支付 5 已支付
                        mDialogStatePayIndex = which
                        mCurStatePay = when (which) {
                            1 -> 0
                            2 -> 5
                            else -> null
                        }
                        mPayStateTv.text = "支付状态：${DataApi.mStatePayArray[mDialogStatePayIndex]}"
                        dialog.dismiss()
                    }.show().apply {
                        DialogUtil.hideNavigationBar(this.window)
                    }
            }
        RxView.clicks(mPayTypeTv)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                AlertDialog.Builder(this)
                    .setTitle("请选择支付状态:")
                    .setCancelable(true)
                    .setSingleChoiceItems(mPayTypeArray, mDialogPayTypeIndex) { dialog, which ->
                        mDialogPayTypeIndex = which
                        mCurPayType = when (which) {
                            1 -> 0//现金支付
                            2 -> 4//会员卡支付
                            3 -> 6//聚合支付
                            4 -> 7//微会员
                            5 -> 8//微会员
                            else -> null
                        }
                        mPayTypeTv.text = "支付类型：${mPayTypeArray[which]}"
                        dialog.dismiss()
                    }.show().apply {
                        DialogUtil.hideNavigationBar(this.window)
                    }

            }
        mResetFilterTv.setOnClickListener {
            //重置筛选条件
            mPage = 0 //从
            mDateBegin = null
            mDateEnd = null
            mStartEntity = null
            mSearchDay = null
            mCurStatePay = null//支付状态
            mCurPayType = null//支付类型
            mPayStateTv.text = "支付状态：已支付"
            mPayTypeTv.text = "支付类型：全部"
            mStartTimeTv.text = "开始时间"
            mEndTimeTv.text = "结束时间"
            setSearchTvFalse()
            getData()
        }
        RxView.clicks(mStartTimeTv)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                DialogConfig.setDialogStyle(DialogStyle.Three)
                if (mStartPicker == null) {
                    mStartPicker = DatimePicker(this)
                    val wheelLayout = mStartPicker!!.wheelLayout
                    mStartPicker!!.setOnDatimePickedListener { year, month, day, hour, minute, second ->
                        mDateBegin = "$year-${String.format("%02d", month)}-${String.format("%02d", day)} ${String.format("%02d", hour)}:${String.format("%02d", minute)}:${String.format("%02d", second)}"
                        mStartTimeTv.text = mDateBegin
                        var startCalendar = Calendar.getInstance()
                        startCalendar.set(year, month - 1, day, hour, minute, second)
                        mStartEntity = DatimeEntity().apply {
                            date = DateEntity.target(startCalendar)
                        }
                        mEndTimeTv.text = "结束时间"
                        mDateEnd = null
                        mEndPicker = null
                    }
                    wheelLayout.setDateMode(DateMode.YEAR_MONTH_DAY)
                    wheelLayout.setTimeMode(TimeMode.HOUR_24_NO_SECOND)
                    val target = DateEntity.target(2023, 1, 1)
                    val datimeEntity = DatimeEntity()
                    datimeEntity.date = target
                    wheelLayout.setRange(datimeEntity, DatimeEntity.now()) //设置选择时间范围
                    wheelLayout.setDefaultValue(DatimeEntity.now()) //设置默认当选时间
                    wheelLayout.setDateLabel("年", "月", "日")
                    wheelLayout.setTimeLabel("时", "分", "秒")
                }
                mStartPicker?.show()
                mStartPicker?.let { DialogUtil.hideNavigationBar(it.window) }
            }
        RxView.clicks(mEndTimeTv)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                DialogConfig.setDialogStyle(DialogStyle.Three)
                if (mDateBegin == null) {
                    ToastUtil.showToast("请选择开始时间")
                    return@subscribe
                }
                if (mEndPicker == null) {
                    mEndPicker = DatimePicker(this)
                    val wheelLayout = mEndPicker!!.wheelLayout
                    mEndPicker!!.setOnDatimePickedListener { year, month, day, hour, minute, second ->
                        mDateEnd = "$year-${String.format("%02d", month)}-${String.format("%02d", day)} ${String.format("%02d", hour)}:${String.format("%02d", minute)}:${String.format("%02d", second)}"
                        mEndTimeTv.text = mDateEnd
                        var t1 = CommUtils.YMD2s(mDateEnd, "yyyy-MM-dd HH:mm:ss") ?: 0L
                        var t2 = CommUtils.YMD2s(mDateBegin, "yyyy-MM-dd HH:mm:ss") ?: 0L
                        if (t1 < t2) { //结束时间 < 开始时间 位置互换。
                            var temp = mDateBegin
                            mDateBegin = mDateEnd
                            mDateEnd = temp
                            mStartTimeTv.text = mDateBegin
                            mEndTimeTv.text = mDateEnd
                        }
                        //去掉选中快捷键1、3、7、30
                        mSearchDay = null
                        setSearchTvFalse()
                    }
                    wheelLayout.setDateMode(DateMode.YEAR_MONTH_DAY)
                    wheelLayout.setTimeMode(TimeMode.HOUR_24_NO_SECOND)
                    wheelLayout.setRange(mStartEntity, DatimeEntity.now()) //设置选择时间范围
                    wheelLayout.setDefaultValue(DatimeEntity.now()) //设置默认当选时间
                    wheelLayout.setDateLabel("年", "月", "日")
                    wheelLayout.setTimeLabel("时", "分", "秒")
                }
                mEndPicker?.show()
                mEndPicker?.let { DialogUtil.hideNavigationBar(it.window) }
            }
        RxView.clicks(mFilterSearchTv)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                if (mDateBegin != null && mDateEnd == null) {
                    ToastUtil.showToast("请选择结束时间!")
                    return@subscribe
                }
                getData()
            }
    }

    override fun getRootLayout(): View = mRootLayout
    override fun onErrorChildClick() = getData()
    override fun onEmptyChildClick() = getData()

    /*加载更多*/
    private fun loadMore() {
        NormalApi.getServerOrderData(
            sortedMapOf(
                Params.start_time to mDateBegin,
                Params.end_time to mDateEnd,
                Params.status to mCurStatePay,
                Params.pay_type to mCurPayType,
                //Params.time_type to mSearchDay,
                Params.size to mPageSize,
                Params.page to mPage
            ), Urls.getCompanyOrder
        )
            .compose(RxUtils.io())
            .compose(RxUtils.aLifecycle(this))
            .subscribe(object : NormalObserver<OrderServerBean>(this) {
                override fun onSuccessNext(t: BaseBean<out OrderServerBean>) {
                    setData(false, t.data?.list?.toMutableList())
                    loadDataSuccess(t.data!!)
                    mSearchAdapter.setEnableLoadMore(true)
                }

                override fun dataIsNull(t: BaseBean<out OrderServerBean>) {
                    super.dataIsNull(t)
                    mSearchAdapter.loadMoreEnd(false)
                }

                override fun onError(e: Throwable) {
                    super.onError(e)
                    mSearchAdapter.loadMoreFail()
                }
            })
    }

    open fun getData() {
        mPage = 1
        NormalApi.getServerOrderData(
            sortedMapOf(
                Params.start_time to mDateBegin,
                Params.end_time to mDateEnd,
                Params.status to mCurStatePay,
                Params.pay_type to mCurPayType,
                //Params.time_type to mSearchDay,
                Params.size to mPageSize,
                Params.page to mPage
            ), Urls.getCompanyOrder
        )
            .compose(RxUtils.io())
            .compose(RxUtils.aLifecycle(this))
            .subscribe(object : StatusLayoutObserver<OrderServerBean>(this, mStatusLayoutManager) {
                override fun onSuccessNext(t: BaseBean<out OrderServerBean>) {
                    mStatusLayoutManager.showSuccessLayout()
                    mData = t.data!!
                    t.data?.list?.firstOrNull()?.item_type = 1
                    updateOrderInfo(t.data?.list?.firstOrNull())
                    setData(true, t.data?.list?.toMutableList())
                    loadDataSuccess(t.data!!)
                    initServerDataAfter()
                    mSearchAdapter.setEnableLoadMore(true)
                }

                override fun dataIsNull(t: BaseBean<out OrderServerBean>) {
                    mSearchAdapter.setNewData(null)
                    super.dataIsNull(t)
                }
            })
    }

    /*获取数据后初始化布局，否则找不到控件对象。*/
    @SuppressLint("CheckResult", "SetTextI18n")
    private fun initServerDataAfter() {
        mSmartRefreshLayout.setOnRefreshListener { refresh() }
        mSearchAdapter.setOnLoadMoreListener({ loadMore() }, mSearchRecyclerView)

        RxView.clicks(mPrintOneTv)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                val find = mSearchAdapter.data.find { it.item_type == 1 }
                if (find != null) {
                    PrinterAll.printOrder(PrintOrderBean.orderServerBean2PrintOrderBean(find))
                } else {
                    ToastUtil.showToast("未找到本单数据!")
                }
            }
        RxView.clicks(mPrintAllTv)
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                //TODO:打印汇总
                if (mData != null) {
                    //TODO:搞到这里啦。
                    PrinterAll.printServerCollectOrder(PrintServerCollectOrderBean.toPrintBean(mData))
                } else {
                    ToastUtil.showToast("未找到汇总数据!")
                }
            }
    }


    private fun updateSearchDayUI(searchTv: TextView, day: Int) {
        setSearchTvFalse()
        searchTv.isSelected = mSearchDay != day
        mSearchDay = if (searchTv.isSelected) day else null

        if (mSearchDay != null) {
//            var start = when (day) {
//                1, 3, 7, 30 -> CommUtils.toYMD_HMS(CommUtils.YMD2s(CommUtils.toYMD(System.currentTimeMillis() / 1000 - (day - 1) * 3600 * 24 + 60)))
//                else -> CommUtils.toYMD_HMS(System.currentTimeMillis() / 1000 - day * 3600 * 24)
//            }
            var start = CommUtils.toYMD_HMS(CommUtils.YMD2s(CommUtils.toYMD(System.currentTimeMillis() / 1000 - (day - 1) * 3600 * 24 + 60)))
            var end = CommUtils.toYMD_HMS(System.currentTimeMillis() / 1000)
            mDateBegin = start
            mDateEnd = end
            mStartTimeTv.text = mDateBegin
            mEndTimeTv.text = mDateEnd
        } else {
            mDateBegin = null
            mDateEnd = null
            mStartTimeTv.text = "开始时间"
            mEndTimeTv.text = "结束时间"
        }
    }

    private fun setSearchTvFalse() {
        mTodaySearchTv.isSelected = false
        mThreeDayTv.isSelected = false
        mSevenSearchTv.isSelected = false
        mMonthSearchTv.isSelected = false
    }

    /*下拉刷新*/
    private fun refresh() {
        mPage = 1
        mSearchAdapter.setEnableLoadMore(false) //这里的作用是防止下拉刷新的时候还可以上拉加载
        NormalApi.getServerOrderData(
            sortedMapOf(
                Params.start_time to mDateBegin,
                Params.end_time to mDateEnd,
                Params.status to mCurStatePay,
                Params.pay_type to mCurPayType,
                //Params.time_type to mSearchDay,
                Params.size to mPageSize,
                Params.page to mPage
            ), Urls.getCompanyOrder
        )
            .compose(RxUtils.io())
            .compose(RxUtils.aLifecycle(this))
            .subscribe(object : NormalObserver<OrderServerBean>(this) {
                override fun onSuccessNext(t: BaseBean<out OrderServerBean>) {
                    mData = t.data!!
                    t.data?.list?.firstOrNull()?.item_type = 1
                    updateOrderInfo(t.data?.list?.firstOrNull())
                    setData(true, t.data?.list?.toMutableList())
                    loadDataSuccess(t.data!!)
                    mSearchAdapter.setEnableLoadMore(true) //结束刷新
                    mSmartRefreshLayout.finishRefresh()
                }

                override fun dataIsNull(t: BaseBean<out OrderServerBean>) {
                    super.dataIsNull(t)
                    mSearchAdapter.setEnableLoadMore(true)
                    mSmartRefreshLayout.finishRefresh()
                }

                override fun onError(e: Throwable) {
                    super.onError(e)
                    mSearchAdapter.setEnableLoadMore(true)
                    mSmartRefreshLayout.finishRefresh(false) //结束刷新（刷新失败）
                }
            })
    }

    private fun setData(isRefresh: Boolean, data: MutableList<OrderServerBean>?) {
        mPage++
        val size = data?.size
            ?: 0
        if (isRefresh) {
            mSearchAdapter.setNewData(data)
        } else {
            if (size > 0) {
                mSearchAdapter.addData(data!!)
            }
        }
        if (size < mPageSize) {
            //第一页如果不够一页就不显示没有更多数据布局
            mSearchAdapter.loadMoreEnd(isRefresh)
        } else {
            mSearchAdapter.loadMoreComplete()
        }
    }

    @SuppressLint("SetTextI18n")
    private fun loadDataSuccess(data: OrderServerBean) {
        val stat = data.stat
        mTotalCountTv.text = "（共 ${data.count} 笔数）"
        mFindZeroTv.text = "找零￥${stat?.di_price ?: "0.00"}"
        mTotalPriceTv.text = "￥${stat?.r_price ?: "0.00"}"
        mDiscountPercentTv.text = "￥${stat?.d_price ?: "0.00"}"
        mRealIncomeTv.text = "￥${stat?.t_price ?: "0.00"}"
    }

    private fun initSearchRecyclerView() {
        (mSearchRecyclerView.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false //去闪烁
        mSearchRecyclerView?.addItemDecoration(
            DividerItemDecoration(
                this, DividerItemDecoration.HORIZONTAL_LIST,
                resources.getDimension(R.dimen.common_measure_1dp).toInt(),
                ContextCompat.getColor(App.context!!, R.color.c6), true
            )
        )
        mSearchAdapter = SearchAdapter()
        mSearchRecyclerView.layoutManager = LinearLayoutManager(this)
        mSearchRecyclerView.adapter = mSearchAdapter
        mSearchAdapter.bindToRecyclerView(mSearchRecyclerView)
        mSearchAdapter.setEmptyView(R.layout.layout_status_layout_manager_empty1)
    }

    private fun initProductRecyclerView() {
        (mProductRecyclerView.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false //去闪烁
        mProductAdapter = ProductAdapter()
        mProductRecyclerView.layoutManager = LinearLayoutManager(this)
        mProductRecyclerView.adapter = mProductAdapter
        mProductAdapter.bindToRecyclerView(mProductRecyclerView)
        mProductAdapter.setEmptyView(R.layout.layout_status_layout_manager_empty1)
    }

    /*搜索列表 适配器*/
    inner class SearchAdapter : BaseMultiItemQuickAdapter<OrderServerBean, BaseViewHolder>(null) {

        init {
            addItemType(0, R.layout.item_order_server_search_unselected)
            addItemType(1, R.layout.item_order_server_search_selected)
        }

        @SuppressLint("CheckResult", "NotifyDataSetChanged")
        override fun convert(helper: BaseViewHolder, item: OrderServerBean) {
            helper
                .setText(R.id.item_tv1, item.pay_type_title)
                .setText(R.id.item_tv2, item.total_price)
                .setText(R.id.item_tv3, item.time)
                .setGone(R.id.item_tv4, item.status_member == 0)



            RxView.clicks(helper.itemView)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe {
                    mData.forEach { it.item_type = 0 }
                    val orderDB = mData[helper.bindingAdapterPosition]
                    orderDB.item_type = 1
                    notifyDataSetChanged()
                    updateOrderInfo(orderDB)
                }
        }
    }

    /*商品列表 适配器*/
    inner class ProductAdapter : BaseQuickAdapter<OrderServerBean, BaseViewHolder>(R.layout.item_order_server_product, null) {
        @SuppressLint("CheckResult", "NotifyDataSetChanged")
        override fun convert(helper: BaseViewHolder, item: OrderServerBean) {
            var discount = if (item.discount == 1.0) "" else " (折后${String.format("%.2f", item.discount * (item.price?.toDouble() ?: 0.0))})"
            var num = if (item.unit == 1) item.weight else if (item.unit == 2) item.number else item.weight
            helper
                .setText(R.id.item_tv1, (helper.bindingAdapterPosition + 1).toString())
                .setText(R.id.item_tv2, item.name)
                .setText(R.id.item_tv3, num/*.plus("/")*/.plus(item.unit_name))
                .setText(R.id.item_tv4, String.format("%.2f", item.price?.toDouble() ?: 0.0).plus(discount))
                .setText(R.id.item_tv5, String.format("%.2f", item.subtotal?.toDouble() ?: 0.0))
                .setText(R.id.item_tv6, String.format("%.2f", item.preferential_amount?.toDouble() ?: 0.0))
                .getView<View>(R.id.item_root_view).apply {
                    setBackgroundColor(if (helper.bindingAdapterPosition % 2 == 0) CommUtils.getColor(R.color.GC9E2F3) else CommUtils.getColor(R.color.grey_EBF3FB))
                }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun updateOrderInfo(orderServerBean: OrderServerBean?) {
        if (orderServerBean == null) return
        mProductAdapter.setNewData(orderServerBean.detail)

        mOrderSnTv.text = orderServerBean.order_sn.isNotAvailable()
        mOrderCreateTimeTv.text = orderServerBean.pay_date.isNotAvailable()
        mOrderOperationUserTv.text = orderServerBean.operation_name.isNotAvailable()


        var tips1 = "商品总额：￥${orderServerBean.all_price}；订单总金额：￥${orderServerBean.order_price}"
        mOrderPriceTv.text = tips1


        var od = if (orderServerBean.discount == 1.0) "" else "(${String.format("%.1f", orderServerBean.discount * 10.0)}折)"
        var tips2 = "商品优惠：￥${orderServerBean.goods_discount_amount}；整单优惠${od}：￥${orderServerBean.discount_amount}"
        mOrderDiscountTv.text = tips2

        var fz = if (orderServerBean.diff_price == 0.0) "" else ", 找零￥${orderServerBean.diff_price}"
        val tips3 = "${orderServerBean.pay_type_title ?: ' '}￥${orderServerBean.total_price}${fz}"
        mOrderRealPriceTv.text = tips3
    }

}